package com.cqw.ftp.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;

import lombok.extern.slf4j.Slf4j;

/**
 * ftp客户端辅助bean  
 */
@Slf4j
public class FTPClientHelper {

	@Autowired
	private FTPClientPool  ftpClientPool;


    /**
     * 下载remote文件流  
     * @param remote 远程文件
     * @return 字节数据
     * @throws Exception
     */
	public   byte[] retrieveFileStream(String remote) throws Exception {
		FTPClient client=null;
		InputStream in =null;
	    try {
	    	  long start =System.currentTimeMillis();
	    	   client=	ftpClientPool.borrowObject();
	    	   in=client.retrieveFileStream(remote);
             
	    	  long end =System.currentTimeMillis();
	    	  System.out.println("ftp下载耗时(毫秒):"+(end-start));
	    	
	    	  if(in != null){
	    		  return   ByteUtil.inputStreamToByteArray(in);
	    	  }else{
	    		  return new byte[0];
	    	  }
		}catch(Exception e){
			log.error("获取ftp下载流异常",e);
		}finally{
			  if (in != null) {  
	                in.close();  
	            } 
			  if(client != null){
				  client.logout();  
				  client.disconnect();
			  }
			ftpClientPool.returnObject(client);
		}
	    return null;
	}
	
	/**
	 * 创建目录    单个不可递归
	 * @param pathname 目录名称
	 * @return
	 * @throws Exception
	 */
	public boolean makeDirectory(String pathname) throws Exception {
		
		FTPClient client=null;
	    try {
	    	client=	ftpClientPool.borrowObject();
			return  client.makeDirectory(pathname);
		} catch(Exception e){
			log.error("创建目录失败",e);
			throw e;
		} finally{
			ftpClientPool.returnObject(client);
		}
	}
	
	

	
	
	
	
	/**
	 * 删除目录，单个不可递归
	 * @param pathname
	 * @return
	 * @throws IOException
	 */
	public   boolean removeDirectory(String pathname) throws Exception {
		FTPClient client=null;
	    try {
	    	client=	ftpClientPool.borrowObject();
			return  client.removeDirectory(pathname);
		} catch(Exception e){
			log.error("删除目录失败",e);
			throw e;
		}  finally{
			ftpClientPool.returnObject(client);
		}
	}
	
	/**
	 * 删除文件 单个 ，不可递归 
	 * @param pathname
	 * @return
	 * @throws Exception
	 */
	public   boolean deleteFile(String pathname) throws Exception {
		
		FTPClient client=null;
	    try {
	    	client=	ftpClientPool.borrowObject();
			return  client.deleteFile(pathname);
		} catch(Exception e){
			log.error("创建文件失败",e);
			throw e;
		} finally{
			ftpClientPool.returnObject(client);
		}
	}
	
	/**
	 * 上传文件 
	 * @param remote
	 * @param local
	 * @return
	 * @throws Exception
	 */
	public   boolean storeFile(String remote, InputStream local) throws Exception {
		FTPClient client=null;
	    try {
	    	client=	ftpClientPool.borrowObject();
			return  client.storeFile(remote, local);
		} catch(Exception e){
			log.error("上传文件失败",e);
			throw e;
		}  finally{
			ftpClientPool.returnObject(client);
		}
	}
	
	/**
	 * @description 取得相对于当前连接目录的某个目录下所有文件列表
	 * @author cqw
	 * @date 2019年11月26日下午8:24:22
	 * @param path
	 * @return
	 * @throws Exception
	 */
//	@SuppressWarnings("static-access")
	public   List<String> getFileList(String path) {
		List<String> fileNames = new ArrayList<String>();
		FTPClient ftpClient = null;
		try {
			ftpClient =	ftpClientPool.borrowObject();
//			ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			FTPFile[] fTPFiles = ftpClient.listFiles(path);
			if(fTPFiles != null) {
				for(FTPFile file : fTPFiles) {
					if(file.isFile()) {
						fileNames.add(file.getName());
					}
				}
			}
		} catch(Exception e){
			log.error("失败",e);
			e.printStackTrace();
		}  finally{
			ftpClientPool.returnObject(ftpClient);
		}
		return fileNames;
	}
	
//	@SuppressWarnings("static-access")
	public   List<String> getTxtList(String path) {
		List<String> fileNames = new ArrayList<String>();
		FTPClient ftpClient = null;
		try {
			ftpClient =	ftpClientPool.borrowObject();
//			ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			FTPFile[] fTPFiles = ftpClient.listFiles(path);
			if(fTPFiles != null) {
				for(FTPFile file : fTPFiles) {
					if(file.getName().endsWith(".txt")) {
						fileNames.add(file.getName());
					}
				}
			}
		} catch(Exception e){
			log.error("失败",e);
			e.printStackTrace();
		}  finally{
			ftpClientPool.returnObject(ftpClient);
		}
		return fileNames;
	}
	
	
    /** * 下载文件 * 
    * @param filenames 文件名称 *
    * @param localpath 下载后的文件路径 * 
    * @return */
    public boolean downloadFile(List<String> filenames, String localpath){
        boolean flag = false; 
        OutputStream os = null;
        FTPClient ftpClient = null;
        try {
            log.info("开始下载文件");
            ftpClient =	ftpClientPool.borrowObject();
//            //切换FTP目录
//            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles(); 
            for(FTPFile file : ftpFiles){
            	String ftpFileName = file.getName();
                if(filenames.contains(ftpFileName)){
                    File localFile = new File(localpath + "/" + ftpFileName);
                    os = new FileOutputStream(localFile); 
                    ftpClient.retrieveFile(ftpFileName, os);
                    os.close(); 
                }
            }
            flag = true; 
            log.info("下载文件成功");
        } catch (Exception e) { 
            log.info("下载文件失败");
            e.printStackTrace(); 
        } finally{ 
            if(null != os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } 
            } 
            ftpClientPool.returnObject(ftpClient);
        } 
        return flag; 
    }
    /** * 删除文件 * 
    * @param pathname FTP服务器保存目录 * 
    * @param filename 要删除的文件名称 * 
    * @return */ 
	public boolean deleteFile(String pathname, String filename) {
		boolean flag = false;
		FTPClient ftpClient = null;
		try {
			ftpClient =	ftpClientPool.borrowObject();
			ftpClient.changeWorkingDirectory(pathname); 
            ftpClient.dele(filename); 
            flag = true;
		} catch(Exception e){
			log.error("上传文件失败",e);
			e.printStackTrace();
		}  finally{
			ftpClientPool.returnObject(ftpClient);
		}
		return flag;
	}
	
	
    /**
    * 上传文件
    * @param pathname ftp服务保存地址
    * @param fileName 上传到ftp的文件名
    *  @param originfilename 待上传文件的名称（绝对地址） * 
    * @return
    */
//	@SuppressWarnings("static-access")
	public boolean uploadFile( String pathname, String fileName,String originfilename) {
		boolean flag = false;
		FTPClient ftpClient = null;
		InputStream inputStream = null;
		try {
			ftpClient =	ftpClientPool.borrowObject();
			log.info("开始上传文件");
            File file = new File(originfilename);
            inputStream = new FileInputStream(file);
//            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.storeFile(fileName, inputStream);
            log.info("上传文件成功！");
            flag = true;
		} catch(Exception e){
			log.error("上传文件失败",e);
			e.printStackTrace();
		}  finally{
			if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } 
            } 
			ftpClientPool.returnObject(ftpClient);
		}
		return flag;
	}
	public boolean uploadFile( String pathname, String fileName,String originfilename ,int num) {
		boolean flag = false;
		FTPClient ftpClient = null;
		InputStream inputStream = null;
		try {
			ftpClient =	ftpClientPool.borrowObject();
			log.info("开始上传文件");
			File file = new File(originfilename);
			inputStream = new FileInputStream(file);
//            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			ftpClient.makeDirectory(pathname);
			ftpClient.changeWorkingDirectory(pathname);
			ftpClient.storeFile(fileName, inputStream);
			log.info("上传文件成功！");
			flag = true;
		} catch(Exception e){
			log.error("上传文件失败",e);
			if( num-- > 0 ) {
				log.info("重试！" + num);
				uploadFile(pathname, fileName, originfilename,num);
			}else {
				e.printStackTrace();
			}
		}  finally{
			if(null != inputStream){
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				} 
			} 
			ftpClientPool.returnObject(ftpClient);
		}
		return flag;
	}
   
}
